<?php
/**

 //  DoYouHaoBaby-X Ucenter ( DoYouHaoBaby-X 计划 )
 //  +---------------------------------------------------------------------
 //
 //  “Copyright”
 //  +---------------------------------------------------------------------
 //	 | (C) 2010 - 2011 http://doyouhaobaby.net All rights reserved.
 //	 | This is not a free software, use is subject to license terms
 //  +---------------------------------------------------------------------
 //
 //  “About This File”
 //  +---------------------------------------------------------------------
 //	 | Ucenter 数据库备份处理控制器
 //  +---------------------------------------------------------------------

*/

!defined( 'DYHB_PATH' ) && exit;

class BackupController extends InitController{

	/**
	 * 数据库备份界面
	 */
	public function index( ){

        $oDb = Db::RUN( );

		$arrTables = $oDb->getConnect()->getCol( "SHOW TABLES LIKE '".G::C('DB_PREFIX')."%'" );

		if( is_array( $arrTables ) ){

			foreach( $arrTables as $sKey => $sTable ){

			    if( $oDb->getConnect()->isViewExists( $sTable ) ){//剔除视图

                    unset( $arrTables[ $sKey ] );
		        }
			}
		}

        $nAllowMaxSize = E::returnBytes( ini_get('upload_max_filesize') ); // 单位为字节
        $nAllowMaxSize = $nAllowMaxSize / 1024; // 转换单位为 KB

	     // 权限检查
         $nMask = E::fileModeInfo( APP_BACKUP_PATH );

         if ( $nMask === false){

             $this->assign( 'sWarning', G::L( "备份目录不存在%s",'app',null,APP_BACKUP_PATH ) );
         }

         else if ( $nMask != 15 ){

            $sWarning = G::L( "文件权限警告：".APP_BACKUP_PATH,'app',null,APP_BACKUP_PATH );

            if ( ( $nMask & 1 ) < 1 ){

                $sWarning .= G::L( '不可读');
            }

            if ( ($nMask & 2) < 1 ){

                $sWarning .= G::L( '不可写');
            }

            if ( ($nMask & 4) < 1){

                $sWarning .= G::L( '不可增加');
            }

            if ( ($nMask & 8) < 1 ){

                $sWarning .= G::L( '不可修改');
            }

            $this->assign('sWarning', $sWarning );
        }

        $this->assign( 'arrTables',   $arrTables );
        $this->assign('nVolSize', $nAllowMaxSize );
        $this->assign( 'sSqlName', Backup::getRandomName() . '.sql' );
	    $this->display( );
	}

	/**
	 * 备份数据库
	 */
	public function dumpsql( ){

        $oDb = Db::RUN( );

       	// 权限检查
        $nMask = E::fileModeInfo( APP_BACKUP_PATH );

         if ( $nMask === false){

             $this->assign( 'sWarning', G::L( "备份目录不存在%s",'app',null,APP_BACKUP_PATH ) );
         }

         else if ( $nMask != 15 ){

            $sWarning = G::L( "文件权限警告：".APP_BACKUP_PATH,'app',null,APP_BACKUP_PATH );

            if ( ( $nMask & 1 ) < 1 ){

                $sWarning .= G::L( '不可读');
            }

            if ( ($nMask & 2) < 1 ){

                $sWarning .= G::L( '不可写');
            }

            if ( ($nMask & 4) < 1){

                $sWarning .= G::L( '不可追加');
            }

            if ( ($nMask & 8) < 1 ){

                $sWarning .= G::L( '不可修改');
            }

            $this->assign('sWarning', $sWarning );
      }

      // 设置最长执行时间为5分钟
      @set_time_limit( 300 );

      // 初始化
      $oConnect = $oDb->getConnect(  );

      $oBackup = new Backup( $oConnect );
      $sRunLog = APP_BACKUP_PATH.'/run.log';

      $sSqlFileName = Safe::getGpc( 'sql_file_name' );

      // 初始化输入变量
      if ( empty( $sSqlFileName ) ){

         $sSqlFileName = BackUp::getRandomName( );
      }

      else{

         $sSqlFileName = str_replace( "0xa", '', trim( $sSqlFileName ) ); // 过滤 0xa 非法字符
         $nPos = strpos( $sSqlFileName, '.sql' );
         if ( $nPos !== false ){

            $sSqlFileName = substr( $sSqlFileName, 0, $nPos );
         }
      }

      $nMaxSize = Safe::getGpc( 'vol_size' );
      $nMaxSize = empty( $nMaxSize ) ? 0 : intval( $nMaxSize );

      $nVol = Safe::getGpc( 'vol' );
      $nVol = empty( $nVol ) ? 1 : intval( $nVol );

      $bIsShort = Safe::getGpc( 'ext_insert' );
      $bIsShort = $bIsShort ==0 ? false : true;

      $oBackup->setIsShort( $bIsShort );

      // 变量验证
      $nAllowMaxSize = intval( @ini_get( 'upload_max_filesize' ) ); //单位M

      if ( $nAllowMaxSize > 0 && $nMaxSize > ( $nAllowMaxSize * 1024 ) ){

          $nMaxSize = $nAllowMaxSize * 1024; //单位K
      }

      if ( $nMaxSize > 0){

          $oBackup->setMaxSize ( $nMaxSize * 1024 );
      }

      // 获取要备份数据列表
      $sType = Safe::getGpc( 'type','P' );
      $sType = empty( $sType ) ? '' : trim( $sType );

      $arrTables = array( );
      switch ( $sType ){

         case 'full':

            $arrTemp = $oDb->getConnect()->getCol( "SHOW TABLES LIKE '".G::C( 'DB_PREFIX' )."%'" );
            foreach ( $arrTemp as $sTable ){

            	if( !$oDb->getConnect()->isViewExists( $sTable ,true ) ){ //剔除视图

                    $arrTables[ $sTable ] = -1;
            	}
            }

            $oBackup->putTablesList( $sRunLog, $arrTables );
            break;

         case 'custom':

            foreach ( Safe::getGpc( 'customtables' ) as $sTable){

                $arrTables[ $sTable ] = -1;
            }

            $oBackup->putTablesList( $sRunLog, $arrTables );
            break;
      }

      // 开始备份
      $arrTables = $oBackup->dumpTable( $sRunLog, $nVol );

      if ( $arrTables === false ){

          $this->E( $oBackup->getErrorMessage( ) );
      }

      if ( empty( $arrTables ) ){

          // 备份结束
          if ( $nVol > 1 ){

            // 有多个文件
            if ( !@file_put_contents( APP_BACKUP_PATH.'/' . $sSqlFileName . '_' . $nVol . '.sql', $oBackup->getDumpSql() ) ){

            	$this->E( G::L( "备份文件写入失败%s" ,'app',null ,$sSqlFileName. '_' . $nVol . '.sql' ) );
            }

            $arrList = array();
            for ( $nI = 1; $nI <= $nVol; $nI++ ){

                $arrList[] = array(

                    'name'=>$sSqlFileName . '_' . $nI . '.sql',
                    'href' => __APPPUB__.'/Backup/' . $sSqlFileName . '_' . $nI . '.sql'
                 );
            }

            $arrMessage = array(

               'list' => $arrList
            );

            $this->sql_dump_message( $arrMessage );
         }

         else{

            // 只有一个文件
            if ( !@file_put_contents( APP_BACKUP_PATH.'/'.$sSqlFileName. '.sql', $oBackup->getDumpSql() ) ){

            	$this->E( G::L( '备份文件写入失败%s','app',null,$sSqlFileName . '_' . $nVol . '.sql') );
            };

            $arrList = array(

                array( 'name' => $sSqlFileName . '.sql',
                       'href' => __APPPUB__.'/Backup/'. $sSqlFileName . '.sql'
                )
            );

            $arrMessage= array(

                'list' => $arrList
            );

            $this->sql_dump_message( $arrMessage );
        }

      }

      else{

        // 下一个页面处理
        if ( !@file_put_contents( APP_BACKUP_PATH.'/' . $sSqlFileName . '_' . $nVol . '.sql', $oBackup->getDumpSql() ) ){

            $this->E( G::L( "备份文件无法写入%s",'app',null, $sSqlFileName . '_' . $nVol . '.sql' ) );
        }

        $arrList = array(

            'sql_file_name'=> $sSqlFileName,
            'vol_size' => $nMaxSize,
            'vol' => $nVol+1
        );

        $sLink = G::U( 'backup/dumpsql',$arrList );

        $arrMessage = array(

            'auto_link' =>$sLink,
            'auto_redirect' =>1,
            'done_file'=> $sSqlFileName . '_' . $nVol . '.sql',
            'list'=>$arrList
         );

         $this->sql_dump_message( $arrMessage );
      }

	}

	/**
	 * 备份消息
	 */
	private function sql_dump_message( $arrMessage ){

		$sBackMsg = "<div style=\"text-align:center;margin:auto;\">
                    <span style=\"font-size: 14px; font-weight: bold\">".G::L( '备份成功了' ).( isset( $arrMessage['done_file'] ) ? $arrMessage['done_file'] :'' )."</span><br/>";

       if ( isset( $arrMessage['auto_redirect'] ) && $arrMessage['auto_redirect'] ){

          $this->assign( '__JumpUrl__',$arrMessage['auto_link'] );
          $this->assign( '__WaitSecond__',3 );
       }

       else{

            if( is_array( $arrMessage['list'] ) ){

            	foreach( $arrMessage['list'] as $arrFile ){

                   $sBackMsg .="<a href=\"{$arrFile['href']}\">{$arrFile['name']}</a><br/>";
            	}
            }

            $this->assign( '__JumpUrl__',G::U('backup/restore') );
            $this->assign( '__WaitSecond__',5 );
       }

       $sBackMsg .="</div>";

       $this->S( $sBackMsg );

	}

    /**
	 * 运行sql语句
	 */
	public function runsql(){

	   $sSql = Safe::getGpc( 'sql' );

	   if( !empty( $sSql ) ){

		   $this->assign( 'sSql',$sSql );
		   $this->assign_sql( $sSql );
	   }
	   $this->display();
	}

	/**
	 * 运行sql语句，结果执行
	 */
    private function assign_sql( $sSql ){

    	$oDb = Db::RUN( );
        $sSql = stripslashes( $sSql );

        // 解析查询项
        $sSql = str_replace( "\r", '', $sSql );

        $arrQueryItems = explode( ";\n", $sSql );

        $arrQueryItems = array_filter( $arrQueryItems, 'strlen');

       // 如果是多条语句，拆开来执行
       if ( count( $arrQueryItems ) > 1 ){

           foreach ( $arrQueryItems as $sKey=>$sValue){

              if ( $oDb->getConnect()->query( $sValue ) ){

                  $this->assign( 'nType',1 );
              }

              else{

                  $this->assign( 'nType',  0 );
                  $this->assign( 'sError', $oDb->getConnect()->getErrorMessage( ) );
                  return;
              }

           }

           return;
      }

      // 单独一条sql语句处理
      if ( preg_match("/^(?:UPDATE|DELETE|TRUNCATE|ALTER|DROP|FLUSH|INSERT|REPLACE|SET|CREATE)\\s+/i", $sSql ) ){// 执行，但不返回结果型

         if ( $oDb->getConnect()->query( $sSql ) ){

             $this->assign('nType',  1);
         }

         else{

            $this->assign('nType',  -1);
            $this->assign('sError',$oDb->getConnect()->getErrorMessage( ) );
         }

     }

     // 返回结果
     else {

        $arrData = $oDb->getConnect()->getAllRows( $sSql );

        if ( $arrData===FALSE ){

            $this->assign( 'nType',  -1);
            $this->assign( 'sError', $oDb->getConnect()->getErrorMessage( ) );
        }

        else{

            $sResult = '';

            if (is_array( $arrData ) && isset( $arrData[0] ) ){

                $sResult = "<table class=\"data full\" id=\"checkList\"> \n<thead> \n<tr>";

                $arrKeys = array_keys( $arrData[0] );

                $nNum = count( $arrKeys );
                for ( $nI = 0; $nI < $nNum; $nI++ ){

                    $sResult .= "<th>" . $arrKeys[ $nI ] . "</th>\n";
                }

                $sResult .= "</tr> \n</thead>\n<tbody>\n";
                foreach ( $arrData as $arrData1){

                    $sResult .= "<tr>\n";
                    foreach ( $arrData1 as $sValue ){

                        $sResult .= "<td>" . $sValue . "</td>";
                    }

                    $sResult .= "</tr>\n";
                }

                $sResult .= "</tbody></table>\n";
            }

            else{

                $sResult ="<center><h3>".G::L( "没有发现任何记录!" )."</h3></center>";
            }

            $this->assign( 'nType',   2 );
            $this->assign( 'sResult', $sResult );
         }

       }

    }

    /**
     * 数据库优化页面
     */
    public function optimize(){

    	$oDb = Db::RUN( );

        // 初始化数据
        $nDbVer = $oDb->getConnect()->getVersion( );
        $sSql = "SHOW TABLE STATUS LIKE '" . G::C('DB_PREFIX') . "%'";

        $nNum = 0;
        $arrList= array();

        $arrReuslt = $oDb->getConnect()->getAllRows( $sSql );

        foreach( $arrReuslt as $arrRow ){

         	if( !$oDb->getConnect()->isViewExists( $arrRow['Name'] ,true) ){//剔除视图

              if ( strpos( $arrRow['Name'], '_session') !== false ){

                  $arrRes['Msg_text'] = 'Ignore';
                  $arrRow['Data_free'] = 'Ignore';
              }

              else{

                  $arrRes = $oDb->getConnect()->getRow( 'CHECK TABLE ' . $arrRow['Name'],null,false );
                  $nNum += $arrRow['Data_free'];
              }

              $sType = $nDbVer >= '4.1' ? $arrRow['Engine'] : $arrRow['Type'];
              $sCharset = $nDbVer >= '4.1' ? $arrRow['Collation'] : 'N/A';
              $arrList[] = array('table' => $arrRow['Name'], 'type' => $sType, 'rec_num' => $arrRow['Rows'], 'rec_size' => sprintf(" %.2f KB", $arrRow['Data_length'] / 1024), 'rec_index' => $arrRow['Index_length'],  'rec_chip' => $arrRow['Data_free'], 'status' => $arrRes['Msg_text'], 'charset' => $sCharset );
           }
        }

        unset( $arrReuslt,$sCharset,$sType );

        // 赋值
        $this->assign( 'arrList', $arrList);
        $this->assign('nNum', $nNum );
        $this->display();
    }

    /**
     * 优化数据库表
     */
    public function run_optimize(){

    	$oDb = Db::RUN( );

        $arrTables = $oDb->getConnect()->getCol( "SHOW TABLES LIKE '" . G::C('DB_PREFIX') . "%'" );

        foreach ( $arrTables as $sTable){

           if ( $arrRow = $oDb->getConnect()->getRow( 'OPTIMIZE TABLE ' . $sTable,null,false ) ){

               // 优化出错，尝试修复
               if ( $arrRow['Msg_type'] =='error' && strpos( $arrRow['Msg_text'], 'repair') !== false ){

                   $oDb->getConnect()->query( 'REPAIR TABLE ' . $sTable );
               }
           }
        }

        // 返回
        $this->S( G::L( "数据表优化成功，共清理碎片  %d",'app' , null,Safe::getGpc( 'num' ) ) );
    }

    /**
     * 数据库恢复页面
     */
    public function restore( ){

       $arrList = array();

       // 检查目录
       $nMask = E::fileModeInfo( APP_BACKUP_PATH );

       if ( $nMask === false){

           $this->assign( 'sWarning', G::L( "备份目录不存在%s",'app',null,APP_BACKUP_PATH ) );
       }

       elseif ( ( $nMask & 1 ) < 1){

           $this->assign( 'sWarning', G::L( '不可读') );
       }

       else{

           // 获取文件列表
           $arrRealList = array( );
           $hFolder = opendir( APP_BACKUP_PATH );

           while ( $sFile = readdir( $hFolder ) ){

               if ( strpos( $sFile,'.sql' ) !== false ){

                   $arrRealList[] = $sFile;
               }
           }

           natsort( $arrRealList );

           $arrMatch = array();

           foreach ($arrRealList as $sFile ){

               if ( preg_match( '/_([0-9])+\.sql$/', $sFile, $arrMatch ) ){

                   if ( $arrMatch[1] == 1 ){

                       $nMark = 1;
                   }

                   else{

                       $nMark = 2;
                   }
               }

               else{

                   $nMark = 0;
               }

               $nFileSize = filesize( APP_BACKUP_PATH .'/'. $sFile );

               $arrInfo = Backup::getHead( APP_BACKUP_PATH .'/'. $sFile );

               $arrList[] = array(

                  'name' => $sFile,
                  'add_time' => $arrInfo['date'],
                  'vol' => $arrInfo['vol'],
                  'file_size' => E::numBitunit( $nFileSize ),
                  'mark' => $nMark
               );
           }
       }

       $this->assign( 'arrList', $arrList );
       $this->display();
    }

    /**
     * 数据备份文件删除
     */
    public function remove( ){

        $arrFile = Safe::getGpc( 'file' );

        if ( !empty( $arrFile ) ){

             $arrMFile = array( ); //多卷文件
             $arrSFile = array( ); //单卷文件

             foreach ( $arrFile as $sFile ){

                 if (preg_match('/_[0-9]+\.sql$/', $sFile )){

                      $arrMFile[] = substr( $sFile, 0, strrpos( $sFile, '_' ) );
                 }

                 else{

                      $arrSFile[] = $sFile;
                 }
             }

             if ( $arrMFile ){

                 $arrMFile = array_unique ( $arrMFile );

                 // 获取文件列表
                 $arrRealFile = array();

                 $hFolder = opendir( APP_BACKUP_PATH );

                 while ( $sFile = readdir( $hFolder ) ){

                     if ( preg_match( '/_[0-9]+\.sql$/', $sFile ) && is_file( APP_BACKUP_PATH.'/'. $sFile ) ){

                         $arrRealFile[] = $sFile;
                     }
                 }

                 foreach ( $arrRealFile as $sFile){

                     $sShortFile = substr( $sFile, 0, strrpos( $sFile, '_' ) );
                     if ( in_array( $sShortFile, $arrMFile ) ){

                         @unlink( APP_BACKUP_PATH.'/'. $sFile );
                     }
                 }
              }

              if ( $arrSFile ){

                  foreach ( $arrSFile as $sFile ){

                      @unlink( APP_BACKUP_PATH.'/'. $sFile );
                  }
              }

              $this->S( G::L( "删除备份文件成功了" ) );

          }

          else{

          	  $this->E( G::L( "你没有选择任何文件" ) );
          }

    }

    /**
     * 从服务器恢复数据
     */
    public function import(){

    	$oDb = Db::RUN();

        $bIsContrim = safe::getGpc( 'confirm' );
        $bIsConfirm = empty( $bIsContrim ) ? false : true;

        $sFileName = safe::getGpc( 'file_name' );
        $sFileName = empty( $sFileName ) ? '': trim( $sFileName );

        // 设置最长执行时间为5分钟
        @set_time_limit( 300 );

        if (preg_match('/_[0-9]+\.sql$/', $sFileName )){

            // 多卷处理
            if ( $bIsConfirm == false ){

                 // 提示用户要求确认
            	 $sUrl = G::U( 'backup/import?confirm=1&file_name='. $sFileName );
            	 $this->assign( "__JumpUrl__",$sUrl );
                 $this->assign( '__WaitSecond__',60 );
            	 $this->S( G::L( "你确定要导入? &nbsp;<a href='%s'>确定</a>",'app',null,$sUrl ) );
            }

            $sShortName = substr( $sFileName, 0, strrpos( $sFileName, '_') );

            // 获取文件列表
            $arrRealFile = array( );

            $hFolder = opendir( APP_BACKUP_PATH );

            while ( $sFile = readdir( $hFolder )){

                if ( is_file(APP_BACKUP_PATH.'/' . $sFile) && preg_match('/_[0-9]+\.sql$/', $sFile) ){

                     $arrRealFile[] = $sFile;
                }
            }

            // 所有相同分卷数据列表
            $arrPostList = array();

            foreach ( $arrRealFile as $sFile){

                $sTmpName = substr( $sFile, 0, strrpos( $sFile, '_' ) );

                if ( $sTmpName == $sShortName ){

                    $arrPostList[] = $sFile;
                }
            }

            natsort( $arrPostList );

            // 开始恢复数据
            foreach ($arrPostList as $sFile){

               $arrInfo = Backup::getHead( APP_BACKUP_PATH .'/'. $sFile );

               if (!$this->sql_import( APP_BACKUP_PATH .'/'. $sFile )){

                   $this->E( G::L( "导入数据库备份文件失败" ).'<br/>'.$oDb->getConnect()->getErrorMessage() );
               }

            }

            $this->assign( "__JumpUrl__",G::U('backup/restore'));
            $this->S( G::L( "数据导入成功" ) );
        }

        else{

            // 单卷
            $arrInfo = Backup::getHead( APP_BACKUP_PATH .'/'. $sFileName );

            if ( $this->sql_import( APP_BACKUP_PATH .'/'. $sFileName ) ){

                $this->assign( "__JumpUrl__",G::U('backup/restore'));
                $this->S( G::L( "数据导入成功" ) );
            }

            else{

                $this->E( G::L( "导入数据库备份文件失败" ).'<br/>'.$oDb->getConnect()->getErrorMessage() );
            }
        }
    }

    /**
     * 从本地上传恢复数据
     */
    public function upload_sql( ){

       $oDb = Db::RUN();

       $sSqlFile = APP_BACKUP_PATH.'/upload_database_bak.sql';

       $sSqlVerConfirm = safe::getGpc( 'sql_ver_confirm' );

       if ( empty( $sSqlVerConfirm ) ){

       	    $arrSqlfile = safe::getGpc( 'sqlfile','F' );

            if ( empty( $arrSqlfile ) ) {

                $this->E( G::L( "你没有选择任何文件" ) );
            }

            // 检查上传是否成功
            if ( ( isset($arrSqlfile['error'] )
                  && $arrSqlfile['error'] > 0)
                  || ( !isset($arrSqlfile['error'])
                  && $arrSqlfile['tmp_name'] =='none' ) ){

                $this->E( G::L( '上传文件失败' ) );
            }

            // 检查文件格式
            if ( $arrSqlfile[ 'type' ] == 'application/x-zip-compressed'){

                $this->E( G::L( "不能是zip格式" ) );
            }

           if (!preg_match("/\.sql$/i" , $arrSqlfile['name'])){

               $this->E( G::L( "不是sql格式" ) );
           }

           // 将文件移动到临时文件，避免权限问题
           if( is_file( $sSqlFile ) ){

              unlink( $sSqlFile );
           }
           if ( !move_uploaded_file( $arrSqlfile['tmp_name'] , $sSqlFile ) ){

               $this->E( G::L( "文件移动失败" ) );
           }
        }

        // 获取sql文件头部信息
        $arrSqlInfo = Backup::getHead( $sSqlFile );

        // 检查数据库版本是否正确
        if ( empty( $sSqlVerConfirm ) ){

           if ( empty( $arrSqlInfo['database_ver'] ) ){

               $this->E( G::L( "没有确定数据库版本") );
           }

           else{

               $nSqlVer = $oDb->getConnect()->getVersion( );

               if ( $arrSqlInfo['database_ver'] != $nSqlVer ){

                   $sMessage = "<a href='".G::U('backup/upload_sql?sql_ver_confrim=1')."'>".G::L( "重试" )."</a></br>< href='".G::U('backup/restore')."'>".G::L( "返回" )."</a>";
                   $this->E( $sMessage );
               }

           }

        }

        // 设置最长执行时间为5分钟
        @set_time_limit( 300 );

        if ( $this->sql_import( $sSqlFile ) ){

            if( is_file( $sSqlFile ) ){

               unlink( $sSqlFile );
            }
            $this->S( G::L( '数据库导入成功' ) );
        }

        else{

           if( is_file( $sSqlFile ) ){

              unlink( $sSqlFile );
           }
            $this->E( G::L( '数据库导入失败' ) );
        }

    }

    /**
     * 将数据写入数据库中
     */
    private function sql_import( $sSqlFile ){

    	$oDb = Db::RUN();

    	$nDbVer  = $oDb->getConnect()->getVersion( );

        $sSqlStr = array_filter( file( $sSqlFile ), 'removeComment' );
        $sSqlStr = str_replace("\r", '', implode('', $sSqlStr));

        $arrRet = explode( ";\n", $sSqlStr );
        $nRetCount = count( $arrRet );

        // 执行sql语句
        if ( $nDbVer > '4.1' ){

           for( $nI = 0; $nI < $nRetCount; $nI++ ){

                $arrRet[ $nI ] = trim( $arrRet[ $nI ], " \r\n;" ); //剔除多余信息

                if ( !empty( $arrRet[$nI] ) ){

                    if ((strpos($arrRet[ $nI ], 'CREATE TABLE') !== false) && ( strpos( $arrRet[ $nI ], 'DEFAULT CHARSET='. str_replace('-', '', G::C('DB_CHAR')) )=== false)){

                         // 建表时缺 DEFAULT CHARSET=utf8
                         $arrRet[ $nI ] = $arrRet[ $nI ] . 'DEFAULT CHARSET='. str_replace('-', '', G::C('DB_CHAR'));
                    }

                    $oDb->getConnect()->query( $arrRet[ $nI ] );

                    if( $oDb->getConnect()->getErrorMessage()!='zero-effect' && $oDb->getConnect()->isError() ){

                    	return false;
                    }
                }
            }

        }

        else{

            for( $nI = 0; $nI < $nRetCount; $nI++ ){

                 $arrRet[$nI] = trim($arrRet[$nI], " \r\n;"); //剔除多余信息

                 if ( ( strpos($arrRet[$nI], 'CREATE TABLE') !== false) && (strpos($arrRet[ $nI ], 'DEFAULT CHARSET='. str_replace('-', '', G::C('DB_CHAR')) )!== false)){

                     $arrRet[$nI] = str_replace('DEFAULT CHARSET='. str_replace('-', '', G::C('DB_CHAR')), '', $arrRet[$nI] );
                 }

                 if ( !empty( $arrRet[$nI] ) ){

                     $oDb->getConnect()->query( $arrRet[$nI] );
                     if( $oDb->getConnect()->getErrorMessage()!='zero-effect' && $oDb->getConnect()->isError() ){

                    	return false;
                    }
                 }

             }
       }

       return true;
    }

}

function removeComment( $sVar ){

     return (substr($sVar, 0, 2) != '--');
}
